jQuery.fn.extend({
    catePicker: function(categoryValue, categoryName, type,mustEnd){
        var category = this;
        
        category.append("<select class='category0'></select>");
        
        $.get("${contextPath }/category.htm", {
            action: "readOptions",
            id: 1,
            type: type
        }, function(data){
            category.find(".category0").append('<option value=""></option>').append(data);
            category.find(".category0").change(function(){
                changeGrade(category.find(".category0"));
            });
        });
        
        function changeGrade(tGrade){
            var className = tGrade.attr("class");
            var nextClassName = "category" + (parseInt(className.substring(8, 9)) + 1);
            var nextGrade = category.find("." + nextClassName);
            if (tGrade.val() != '') {
                $.get("${contextPath }/category.htm", {
                    action: "readOptions",
                    id: tGrade.val(),
                    type: type
                }, function(data){
                    if(!mustEnd){
                    	$(categoryValue).val(tGrade.val());
                    	$(categoryName).val(tGrade.find('option:selected').text());
                    }
                    if ($.trim(data) == "") {
                    	if(mustEnd){
                    		$(categoryValue).val(tGrade.val());
                    		$(categoryName).val(tGrade.find('option:selected').text());
                    	}
                        while (nextGrade.length != 0) {
                            nextGrade.hide();
                            className = nextGrade.attr("class");
                            nextClassName = "category" + (parseInt(className.substring(8, 9)) + 1);
                            nextGrade = category.find("." + nextClassName);
                        }
                    }
                    else {
                        if (nextGrade.length == 0) {
                            category.append("<select class='" + nextClassName + "'></select>");
                            category.find("." + nextClassName).change(function(){
                                changeGrade(category.find("." + nextClassName))
                            });
                        }
                        nextGrade = category.find("." + nextClassName);
                        nextGrade.show().html('').append('<option value=""></option>').append(data);
                    }
                });
            }else{
				$(categoryValue).val('');
           		$(categoryName).val('');
           		while (nextGrade.length != 0) {
                	nextGrade.hide();
                	className = nextGrade.attr("class");
               		nextClassName = "category" + (parseInt(className.substring(8, 9)) + 1);
                	nextGrade = category.find("." + nextClassName);
            	}
			}
        }
    }
});
